
import fetch from 'dva/fetch';

function parseJSON(response) {
    return response.json();
}
function checkStatus(response) {
    if (response.status >= 200 && response.status < 300) {
        return response;
    }
    const error = new Error(response.statusText);
    error.response = response;
    throw error;
}

export function request(url, options) {


    return fetch(url, options)
        .then(checkStatus)
        .then(parseJSON)
        .then((data) => {
            // 检测到未登录，直接跳转到登录页面.
            if (data.statusCode === 401) {
                var fromUrl = data.data.replace('api/', '');
                window.location.href = fromUrl.substr(0, fromUrl.lastIndexOf('/'));
            }
            return { data };
        })
        .catch((err) => {
            console.log(err);
            // message.error(err);
        });
}


export function postOptions(values) {
    const options = {
        method: "POST",
        body: JSON.stringify(values),
        headers: { 'Content-Type': 'application/json' }
    };
    return options;
}
export function getOptions(values) {
    const options = {
        method: "GET",
        params: values,
        headers: { 'Content-Type': 'application/json' }
    };
    return options;
}